package org.qydjk.console.service.impl;

import org.qydjk.common.dao.IBaseDao;
import org.qydjk.common.pojo.Category;
import org.qydjk.common.pojo.product.*;
import org.qydjk.common.pojo.user.UserComment;
import org.qydjk.common.pojo.user.UserCommentImgs;
import org.qydjk.common.service.impl.BaseService;
import org.qydjk.common.shiro.vo.ShiroUser;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.util.ThumbnailatorUtils;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.common.vo.ext.ProductLogEnum;
import org.qydjk.console.service.IProductService;
import org.qydjk.console.vo.ProductExtendsBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by Administrator on 2017/12/25 0025.
 */
@Service
public class ProductService extends BaseService implements IProductService {
    @Autowired
    private IBaseDao baseDao;
    /**
     * 添加
     * @param productExtendsBean
     * @param shiroUser
     * @param request
     * @return
     * @throws Exception
     */
    public Boolean addProductALlInfo(ProductExtendsBean productExtendsBean, ShiroUser shiroUser, HttpServletRequest request) throws Exception {
        Boolean flag=false;
        Product product=new Product();
        BeanUtil.copyProperties(productExtendsBean,product);
        product.setCategoryIds(product.getCategoryIds());//分类IDs 产品的分类只有一个
        product.setAreaIds(StringUtil.dotAddStartEnd(product.getAreaIds()));//城市IDs
        product.setThumbnailImg(product.getImg());
        product.setVerifyType(0);//默认:待审核
        product.setStatus(1);//默认:正常
        product.setUpdateTime(new Date());//修改时间
        product.setCreateTime(new Date());//创建时间
        //TODO 产品标签
        List<ProductLabelDetail> plds = new ArrayList<ProductLabelDetail>();
        //TODO 产品属性
        List<ProductAttrDetail> pads = new ArrayList<ProductAttrDetail>();
        StringBuffer sbCode = new StringBuffer();
        Enumeration parmNames = request.getParameterNames();
        while (parmNames.hasMoreElements()){
            String para = (String)parmNames.nextElement();
            if(para.startsWith("label_")){
                String labelCode = para.replace("label_","");
                String labelDetailCode = request.getParameter(para);
                ProductLabelDetail sld = new ProductLabelDetail();
                sld.setSellerProductLabelCode(labelCode);
                sld.setSellerProductLabelDetailCode(labelDetailCode);
                sbCode.append(labelDetailCode).append(",");
                plds.add(sld);
            }else if(para.startsWith("attrs_")){
                String attrCode = para.replace("attrs_","");
                String attrContent = request.getParameter(para);
                if(!StringUtil.isEmptyOrNull(attrContent)){
                    ProductAttrDetail pad = new ProductAttrDetail();
                    pad.setContent(attrContent);
                    pad.setProductAttrCode(attrCode);
                    pad.setCreateTime(new Date());
                    pad.setUpdateTime(new Date());
                    pads.add(pad);
                }
            }
        }
        //TODO 产品标签Codes
        String labelCodes = StringUtil.dotAddStartEnd(sbCode.toString());
        product.setLabelCodes(labelCodes);//标签codes
        Integer productId= (Integer) baseDao.save(product);
        if(productId==null){
            return flag;
        }
        //保存中间表数据
        Boolean ss= saveProductCentreEntity(productExtendsBean,productId,plds,pads);
        if(!ss){
            return flag;
        }

        //日志
        ProductLog productLog=new ProductLog();
        productLog.setProductId(productId);//产品id
        productLog.setUserId(shiroUser.getId()); //管理员id
        productLog.setUserType(2);//用户类型：0商家1员工2后台管理员
        productLog.setUsername(shiroUser.getName());//管理员名称
        productLog.setType(ProductLogEnum.ADD.getType()); //状态:添加
        productLog.setTypeName(ProductLogEnum.ADD.getTypeName());//名称
        productLog.setCreateTime(new Date());
        productLog.setUpdateTime(new Date());
        Integer productLogId= (Integer) baseDao.save(productLog);
        if(productLogId!=null){
            flag=true;
        }
        return flag;
    }

    /***
     * 修改
     * @param productExtendsBean
     * @param shiroUser
     * @param request
     * @return
     * @throws Exception
     */
    public Boolean updateProductALlInfo(ProductExtendsBean productExtendsBean, ShiroUser shiroUser, HttpServletRequest request) throws Exception {
        Boolean flag=false;
        Product product= baseDao.get(Product.class,productExtendsBean.getId());
        BeanUtil.copyProperties(productExtendsBean,product);
        product.setThumbnailImg(product.getImg());
        product.setUpdateTime(new Date());//修改时间
        product.setCategoryIds(product.getCategoryIds());//分类IDs 产品的分类只有一个
        product.setAreaIds(StringUtil.dotAddStartEnd(product.getAreaIds()));//城市IDs
        //TODO 产品标签
        List<ProductLabelDetail> plds = new ArrayList<ProductLabelDetail>();
        //TODO 产品属性
        List<ProductAttrDetail> pads = new ArrayList<ProductAttrDetail>();
        StringBuffer sbCode = new StringBuffer();
        Enumeration parmNames = request.getParameterNames();
        while (parmNames.hasMoreElements()){
            String para = (String)parmNames.nextElement();
            if(para.startsWith("label_")){
                String labelCode = para.replace("label_","");
                String labelDetailCode = request.getParameter(para);
                ProductLabelDetail sld = new ProductLabelDetail();
                sld.setSellerProductLabelCode(labelCode);
                sld.setSellerProductLabelDetailCode(labelDetailCode);
                sbCode.append(labelDetailCode).append(",");
                plds.add(sld);
            }else if(para.startsWith("attrs_")){
                String attrCode = para.replace("attrs_","");
                String attrContent = request.getParameter(para);
                if(!StringUtil.isEmptyOrNull(attrContent)){
                    ProductAttrDetail pad = new ProductAttrDetail();
                    pad.setContent(attrContent);
                    pad.setProductAttrCode(attrCode);
                    pad.setCreateTime(new Date());
                    pad.setUpdateTime(new Date());
                    pads.add(pad);
                }
            }
        }
        String labelCodes = StringUtil.dotAddStartEnd(sbCode.toString());
        product.setLabelCodes(labelCodes);//标签codes
        baseDao.update(product);
        //先执行删除中间表
        baseDao.excuteSQL("DELETE FROM qy_product_category WHERE product_id ="+product.getId());//分类
        baseDao.excuteSQL("DELETE FROM qy_product_label_detail WHERE product_id ="+product.getId());//标签
        baseDao.excuteSQL("DELETE FROM qy_product_attr_detail WHERE product_id ="+product.getId());//属性
        baseDao.excuteSQL("DELETE FROM qy_product_city WHERE product_id ="+product.getId());//城市
        baseDao.excuteSQL("DELETE FROM qy_product_imgs WHERE product_id ="+product.getId());//图片
        //保存中间表数据
        Boolean ss= saveProductCentreEntity(productExtendsBean,productExtendsBean.getId(),plds,pads);
        if(!ss){
            return flag;
        }
        //日志
        ProductLog productLog=new ProductLog();
        productLog.setProductId(productExtendsBean.getId());//产品id
        productLog.setUserId(shiroUser.getId()); //管理员id
        productLog.setUsername(shiroUser.getName());//管理员名称
        productLog.setUserType(2);
        productLog.setType(ProductLogEnum.APPLY_PUTAWAY.getType()); //状态:添加
        productLog.setTypeName(ProductLogEnum.APPLY_PUTAWAY.getTypeName());//名称
        productLog.setCreateTime(new Date());
        productLog.setUpdateTime(new Date());
        Integer productLogId= (Integer) baseDao.save(productLog);
        if(productLogId!=null){
            flag=true;
        }
        return flag;
    }

    /***
     * 待查询 分页 套餐数据显示
     * @author Edward_yang
     * @uptime 2017-12-27
     * @param page
     * @param rows
     * @param keyWord
     * @return
     * @throws Exception
     */
    public EasyUIResponse findProductAllList(Integer page, Integer rows, String keyWord) throws Exception {
        HibernatePage pager = new HibernatePage(page,rows);
        String sql="SELECT  qp.id as id, qs.name as sellerName ,qp.name as productName, qp.img as productImg , qp.origin_price as originPrice ,qp.price as price, qp.repertory as repertory, qp.verify_type as verifyType, qp.status as status, qp.type as type ,qp.virtaul_comment_count  as virtaulCommentCount , qp.virtual_appointment_count as virtualAppointmentCount," +
                "  qp.virtual_collect_account as virtualCollectAccount, qp.virtual_sales_count as virtualSalesCount, qp.sales_count as salesCount, qp.comment_count as commentCount, qp.comment_score as commentScore,qp.appointment_count as appointmentCount, qp.collect_account as collectAccount, qp.create_time as createDate" +
                "  FROM  qy_seller qs ,qy_product qp " +
                " WHERE qs.id=qp.seller_id";
        String countSql="SELECT count(qp.id) "+
                "  FROM  qy_seller qs ,qy_product qp " +
                " WHERE qs.id=qp.seller_id";
        if(!StringUtil.isEmptyOrNull(keyWord)){
            sql+="  and qp.name like '%"+keyWord+"%' or  qs.name like '%"+keyWord+"%'";
            countSql+=" and qp.name like '%"+keyWord+"%' or  qs.name like '%"+keyWord+"%'";
        }
        sql+= " ORDER BY  qp.create_time desc";

            List<Map<String,Object>> productList=baseDao.findMapBySQL(sql,pager);
            int total = baseDao.getRecordCountSQL(countSql);
            return new EasyUIResponse(total,productList);
    }

    /****
     * @author Edward_yang
     * @uptime 2017-12-26
     * @param productExtendsBean
     * @param productId  产品ID
     * @param plds  TODO 产品标签
     * @param pads  TODO 产品属性
     * @return
     * @throws Exception
     */
    public Boolean saveProductCentreEntity(ProductExtendsBean productExtendsBean,Integer productId, List<ProductLabelDetail> plds,  List<ProductAttrDetail> pads)throws Exception {
        Boolean flag=false;
        //产品分类中间表(只有一个)
        String CategoryIdsString=productExtendsBean.getCategoryIds();
        List<Category> CategoryIdsList=baseDao.findBeanBySQL(" select *from qy_category where  id in( "+CategoryIdsString+")",Category.class);
        for(Category category:CategoryIdsList ) {
            ProductCategory productCategory = new ProductCategory();
            productCategory.setCategoryId(category.getId());
            productCategory.setProductId(productId);
            productCategory.setLevel(category.getLevel());//等级
            productCategory.setCreateTime(new Date());
            productCategory.setUpdateTime(new Date());
            baseDao.save(productCategory);
        }
        //标签中间表
        for(ProductLabelDetail pld :plds){
            ProductLabelDetail productLabelDetail=new ProductLabelDetail();
            productLabelDetail.setSellerProductLabelCode(pld.getSellerProductLabelCode());//标签code
            productLabelDetail.setSellerProductLabelDetailCode(pld.getSellerProductLabelDetailCode());//标签明细code
            productLabelDetail.setProductId(productId);
            productLabelDetail.setCreateTime(new Date() );
            productLabelDetail.setUpdateTime(new Date());
            baseDao.save(productLabelDetail);
        }
        //属性中间表
        for(ProductAttrDetail pad:pads){
            ProductAttrDetail productAttrDetail=new ProductAttrDetail();
            productAttrDetail.setProductAttrCode(pad.getProductAttrCode());
            productAttrDetail.setContent(pad.getContent());
            productAttrDetail.setProductId(productId);
            productAttrDetail.setUpdateTime(new Date());
            productAttrDetail.setCreateTime(new Date());
            baseDao.save(productAttrDetail);
        }

        //产品城市中间表
        boolean isSend= sveaProductCity(productExtendsBean.getOneAreaId(),productId,1);
        if(!isSend){return false;}
        isSend=  sveaProductCity(productExtendsBean.getTwoAreaId(),productId,2);
        if(!isSend){return false;}
        if(productExtendsBean.getThreeAreaId()!=null){
            isSend= sveaProductCity(productExtendsBean.getThreeAreaId(),productId,3);
            if(!isSend){return false;}
        }

        //图片中间表
        String ImgsUrlString=productExtendsBean.getImgsUrl();
        String[] ImgsUrl=ImgsUrlString.split(",");
        for(int i=0;i<ImgsUrl.length;i++) {
            ProductImgs productImgs = new ProductImgs();
            productImgs.setImg(ImgsUrl[i].toString());
            productImgs.setThumbnailImg(ImgsUrl[i].toString());
            productImgs.setProductId(productId);
            productImgs.setOrd(i);
            productImgs.setUpdateTime(new Date());
            productImgs.setCreateTime(new Date());
            baseDao.save(productImgs);
        }
        flag=true;

        return flag;
    }

    /***
     *  添加产品城市中间表判断
     * @author Edward_yang
     * @uptime 2017-12-27
     * @param produCtityId
     * @param productId
     * @param level
     * @return
     */
    public  Boolean sveaProductCity(Integer produCtityId,Integer productId,Integer level) throws Exception {
        Boolean flag=false;
        ProductCity productCity=new ProductCity();
        productCity.setProductId(productId);
        productCity.setLevel(level);
        productCity.setAreaId(produCtityId);
        productCity.setCreateTime(new Date());
        productCity.setUpdateTime(new Date());
        Integer productCityID= (Integer) baseDao.save(productCity);
        if(productCityID!=null){
            flag=true;
        }
        return flag;
    }

    /**
     * 添加评论
     * @param userComment
     * @param imgStr
     */
    public void saveComment(UserComment userComment, String imgStr) throws Exception {
       baseDao.save(userComment);
       if (imgStr != null) {
           String[] imgs = imgStr.split(",");
           for (int i = 0; i < imgs.length; i++) {
               UserCommentImgs userCommentImgs = new UserCommentImgs();
               userCommentImgs.setCommentId(userComment.getId());
               userCommentImgs.setImg(imgs[i]);
               userCommentImgs.setThumbnailImg(ThumbnailatorUtils.imgUrlToThumbnaiUrl(imgs[i]));
               userCommentImgs.setCreateTime(userComment.getCreateTime());
               userCommentImgs.setUpdateTime(userComment.getCreateTime());
               baseDao.save(userCommentImgs);
           }
       }
    }

    /**
     * 修改评论
     * @param userComment
     * @param imgStr
     * @throws Exception
     */
    public void updateComment(UserComment userComment,String imgStr) throws Exception {
        baseDao.save(userComment);
        String deleteImgSql = "DELETE FROM qy_user_comment_imgs WHERE comment_id = "+userComment.getId();
        baseDao.excuteSQL(deleteImgSql);

        if (imgStr != null) {
            String[] imgs = imgStr.split(",");
            for (int i = 0; i < imgs.length; i++) {
                UserCommentImgs userCommentImgs = new UserCommentImgs();
                userCommentImgs.setCommentId(userComment.getId());
                userCommentImgs.setImg(imgs[i]);
                userCommentImgs.setThumbnailImg(ThumbnailatorUtils.imgUrlToThumbnaiUrl(imgs[i]));
                userCommentImgs.setCreateTime(userComment.getCreateTime());
                userCommentImgs.setUpdateTime(userComment.getCreateTime());
                baseDao.save(userCommentImgs);
            }
        }

    }

    /**
     * 删除评论
     * @param userComment
     * @throws Exception
     */
    public void deleteComment(UserComment userComment) throws Exception {
        baseDao.delete(userComment);
        String deleteImgSql = "DELETE FROM qy_user_comment_imgs WHERE comment_id = "+userComment.getId();
        baseDao.excuteSQL(deleteImgSql);
    }
}

